#!/bin/bash
#filename auto_reboot.sh

BASE_DIR=$(cd "$(dirname "$0")"; pwd)/

cd $BASE_DIR

# 设置最大CPU占用百分比
PID_CPU_MAX="200"

# 设置最大系统负载
SYS_LOAD_MAX="8"

LOG_FILE=/var/log/autoreboot.log

#tee -a $LOG_FILE

# 自动从*.properties中读取配置,不需要调整shell文件了
APP_CONF_DIR=conf/

# 设置需要监控的服务名称
# NAME_LIST="php-fpm mysql"
NAME_LIST=`cat $APP_CONF_DIR/*.properties |grep "^spring.application.name" | tail -n 1 | cut -d "=" -f2- | awk '{print $1}' |sed -e 's/^\s*//' -e 's/\s*$//'`

PID=`/bin/ps -ef | grep java | grep "$NAME_LIST" | grep -v grep |awk '{print $2}'`

# 初始化CPU统计
PID_CPU_SUM=0

# 获取该程序总进程数
PID_NUM_SUM=`ps aux | grep $NAME_LIST | grep -v grep | wc -l`

if [ $PID_NUM_SUM -eq 0 ]
	then
		sh start.sh
		echo $(date +%H:%M:%S) "   程序 $NAME_LIST 重启成功"  | tee -a $LOG_FILE
		exit
	else
		echo $(date +%H:%M:%S) "   程序 $NAME_LIST 正在运行" | tee -a $LOG_FILE
fi

# 列出每个进程cpu占用百分比
PID_CPU_LIST=`ps aux | grep $NAME_LIST | grep -v grep | awk '{print $3}'`

# 计算所有进程总CPU占用
for PID_CPU in $PID_CPU_LIST
do
	PID_CPU_SUM=`echo $PID_CPU_SUM + $PID_CPU | bc` 
done

# 获取最近一分钟系统负载
SYS_LOAD=`uptime | awk '{print $(NF-2)}' | sed 's/,//'`

# 比较CPU占用和系统负载是否超过阀值
CPU_VULE=`awk 'BEGIN{print('"$PID_CPU_SUM"'>='"$PID_CPU_MAX"'?"1":"0")}'`
LOAD_VULE=`awk 'BEGIN{print('"$SYS_LOAD"'>='"$SYS_LOAD_MAX"'?"1":"0")}'`

# 如果系统CPU占用和系统负载超过阀值，则进行下面操作。
if [[ "$CPU_VULE" = "1" ]] || [[ "$LOAD_VULE" = "1" ]] ;then
	#  写入日志
	echo $(date +"%y-%m-%d %H:%M:%S") "killall $PID $NAME_LIST" "(CPU:$PID_CPU_SUM,LOAD:$SYS_LOAD)" | tee -a $LOG_FILE
	# 正常停止服务
	#/etc/init.d/$NAME_LIST stop
	sh stop.sh
	sleep 3
	# 强制关闭
	pkill $PID

	# 重启
	#/etc/init.d/$NAME_LIST start
	sh start.sh
  #写入日志
	echo $(date +"%y-%m-%d %H:%M:%S") "start $PID $NAME_LIST" "(CPU:$PID_CPU_SUM,LOAD:$SYS_LOAD)"  | tee -a $LOG_FILE
else
	echo $(date +"%y-%m-%d %H:%M:%S") "$PID $NAME_LIST very health!(CPU:$PID_CPU_SUM,LOAD:$SYS_LOAD)"  | tee -a $LOG_FILE
fi
exit
